
from typing import Any, Generic, List, TypeVar
from pydantic import BaseModel, Field
from utils.serialize import serialize_objects


class BaseResponse(BaseModel):
    """http统一响应"""
    code: int = Field(default=200)
    msg: str = Field(default="success")
    data: Any = None
    def to_dict(self):
        return {"code": self.code, "msg": self.msg, "data": self.data}

class SuccessResponse(BaseResponse):
    def __init__(self, data=None, message="Success"):
        super().__init__(code=200, message=message, data=data)

class ErrorResponse(BaseResponse):
    error: Any = None


T = TypeVar('T')
class PageResponse(BaseModel,Generic[T]):
    list: List[T]
    totalCount: int
    def __init__(self, list: List[T], totalCount: int):
        super().__init__(list=list, totalCount=totalCount)
        
def page_list(query, page_index, page_size, isSerializeList=False):
    list = query.offset((page_index - 1) * page_size).limit(page_size).all()
    total_count = query.count()
    if isSerializeList:
        list = serialize_objects(list)
    return PageResponse(list,total_count)